package com.xiaoye.qbdatahandle.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.xiaoye.qbdatahandle.config.XiaoYeConfig;
import com.xiaoye.qbdatahandle.domian.CollectionResult;
import com.xiaoye.qbdatahandle.domian.QbSubjectArticle;
import com.xiaoye.qbdatahandle.result.ElementResultVo;
import com.xiaoye.qbdatahandle.result.ElementsVo;
import com.xiaoye.qbdatahandle.vo.ElementBodyVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.xiaoye.qbdatahandle.util.DateUtils.parseDate;

@Slf4j
@Service
public class CollectionResultService {

    @Autowired
    TextHandleService textHandleService;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * @description: 采集结果清洗入库
     * @author: ChenYao Chen
     * @return: void
     * @ceateDate: 2025/2/27 上午3:21
     */

    public void handleResult() {
        //Criteria criteria = new Criteria();
        Criteria criteria = new Criteria().orOperator(
                Criteria.where("is_handle").exists(false), // 字段不存在
                Criteria.where("is_handle").is(null),    // 字段为 null
                Criteria.where("is_handle").is(false)     // 字段为 false
        );
        // 查询 采集结果 没有清洗结果的集合
        List<CollectionResult> list = mongoTemplate.find(Query.query(criteria).limit(100), CollectionResult.class);

        if (list.isEmpty()) {
            log.info("待清洗数据为空,=================");
            return;
        }
        for (CollectionResult collectionResult : list) {
            // 清洗文本
            try {
                String resultContent = collectionResult.getContent();
                String cleanContent = null;
                QbSubjectArticle qbSubjectArticle = new QbSubjectArticle();
                if (StringUtils.isNotBlank(resultContent)) {
                    cleanContent = textHandleService.cleanText(resultContent, false, String.valueOf(StandardCharsets.UTF_8), qbSubjectArticle);
                    if (StringUtils.isBlank(cleanContent)) {
                        log.info("清洗文本结果为空=================");
                        continue;
                    }
                }
                // 将collectionResult复制 到 QbSubjectArticle

                qbSubjectArticle.setCollectionResultId(collectionResult.getId());
                qbSubjectArticle.setKeywords(setKeywords(collectionResult));
                qbSubjectArticle.setSource(collectionResult.getSource());
                qbSubjectArticle.setUrl(collectionResult.getUrl());
                //qbSubjectArticle.setPublishTime(parseDate(collectionResult.getPublishTime()));
                qbSubjectArticle.setPublishTime(collectionResult.getPublishTime());
                qbSubjectArticle.setTitle(collectionResult.getTitle());
                qbSubjectArticle.setImages(collectionResult.getImages());
                qbSubjectArticle.setContent(cleanContent);
                qbSubjectArticle.setCover(collectionResult.getCover());
                qbSubjectArticle.setCreateTime(DateUtil.now());
                qbSubjectArticle.setUpdateTime(DateUtil.now());
                qbSubjectArticle.setTid(collectionResult.getTid());
                // 采集结果里面的摘要
                String collectionResultIntro = collectionResult.getIntro();
                if (StringUtils.isBlank(collectionResultIntro) && StringUtils.isNotBlank(cleanContent)) {
                    String intro = textHandleService.getIntro(cleanContent);
                    System.out.println("采集结果无摘要信息，生成新情报摘要:" + intro);
                    qbSubjectArticle.setIntro(intro);
                }

                //   关键要素
                qbSubjectArticle.setElementInfo(getKeyElements(cleanContent));
                System.out.println("==============="+qbSubjectArticle.getCollectionResultId());
                // 删除已存在的数据
                mongoTemplate.remove(Query.query(Criteria.where("collect_result_id")
                                .is(qbSubjectArticle.getCollectionResultId()))
                        , QbSubjectArticle.class);
                // 保存到数据库
                mongoTemplate.save(qbSubjectArticle);
                // 更新 采集结果 已清洗字段
                mongoTemplate.updateFirst(
                        Query.query(Criteria.where("_id").is(collectionResult.getId())),
                        new org.springframework.data.mongodb.core.query.Update().set("is_handle", true),
                        CollectionResult.class);


            } catch (UnsupportedEncodingException e) {
                log.error("清洗文本异常:{}", e.getLocalizedMessage());
                //throw new RuntimeException(e);
            }
        }

    }

    @Autowired
    TextAnalyzerService textAnalyzerService;

    private String setKeywords(CollectionResult collectionResult) {
        String keywords = collectionResult.getKeywords();
        if (StringUtils.isNotBlank(keywords)) {
            return keywords;
        }
        // 获取正文 然后使用jieba抽取关键词
        String content = collectionResult.getContent();
        if (StringUtils.isBlank(content)) {
            return null;
        }
        // 使用jieba抽取关键词
        Map<String, Integer> map = textAnalyzerService.analyzeText(content);
        if (map.isEmpty()) {
            return null;
        }
        // 取map的前十个
        return map.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) // 按值降序排序
                .limit(10) // 限制前 10 个
                .map(Map.Entry::getKey) // 提取键
                .collect(Collectors.joining(",")); // 用逗号拼接;
    }

    /**
     * @param content
     * @description: 获取关键要素
     * @author: ChenYao
     * @return: void
     * @ceateDate: 2025/2/25 上午2:50
     */

    public ElementsVo getKeyElements(String content) {
        if (content == null || content.isEmpty()) {
            return null;
        }
        ElementBodyVo elementBodyVo = new ElementBodyVo();
        elementBodyVo.setContent(content);
        // 发送 POST 请求
        String result = HttpRequest.post(XiaoYeConfig.getElementsUrl())
                .header("Content-Type", "application/json") // 设置请求头
                .body(JSONObject.toJSONString(elementBodyVo)) // 设置请求体
                .execute()
                .body();
        System.out.println("关键要素结果:" + result);
        ElementResultVo elementResultVo = JSONObject.parseObject(result, ElementResultVo.class);

        return elementResultVo.getResult();

    }
}
